const db = uniCloud.database()
const collection = db.collection('customer-lifecycle-history')
const dbcmd = db.command

const getEventName = (eventType) => {
	const eventNames = {
		1: "电话录入",
		2: "客户登记",
		3: "分配顾问",
		4: "首次接待",
		5: "再次接待",
		6: "房源带看",
		7: "意向金缴纳",
		8: "签订认购书",
		9: "签订购房合同",
		10: "付款",
		11: "贷款办理",
		12: "交房",
		13: "成交完成",
		14: "客户流失",
		15: "重新激活",
		16: "中介录入",
		17:"随访"
	};
	return eventNames[eventType] || '未知事件';
}

const getDefaultEventDescription = (eventType) => {
	const descriptions = {
		1: '客户首次登记信息',
		2: '为客户分配置业顾问',
		3: '置业顾问首次接待客户',
		4: '置业顾问再次接待客户',
		5: '带客户参观房源',
		6: '客户缴纳意向金',
		7: '客户签订认购书',
		8: '客户签订购房合同',
		9: '客户完成付款',
		10: '协助客户办理贷款',
		11: '完成交房手续',
		12: '客户购房流程全部完成',
		13: '客户流失',
		14: '客户重新激活'
	};
	return descriptions[eventType] || '';
}

// 工具方法：获取当前阶段
const getCurrentStage = (events) => {
	const lastEvent = events[events.length - 1];
	const stageMap = {
		1: '客户登记',
		2: '已分配顾问',
		3: '首次接待完成',
		4: '持续跟进中',
		5: '房源带看中',
		6: '意向金阶段',
		7: '认购阶段',
		8: '合同签订',
		9: '付款中',
		10: '贷款办理中',
		11: '交房中',
		12: '已完成成交',
		13: '已流失',
		14: '重新激活'
	};
	return stageMap[lastEvent.eventType] || '未知阶段';
}


const addLifecycleEvent = async (params) => {
	const {
		customerId,
		eventType,
		eventDescription,
		eventTime,
		consultantId,
		consultantName,
		propertyId,
		propertyName,
		amount,
		paymentType,
		contractNumber,
		documentUrls,
		imageUrls,
		previousStatus,
		currentStatus,
		intentionLevel,
		nextFollowTime,
		isImportant,
		tags,
		visitType,
		operatorName,
		uid
	} = params;



	// 获取客户信息
	const customerCollection = db.collection('sunny-custom');
	const customerRes = await customerCollection.doc(customerId).get();

	if (customerRes.data.length === 0) {
		return {
			code: 200,
			resultCode: -1,
			message: '客户不存在'
		};
	}

	const customerInfo = customerRes.data[0];

	// 构建事件数据
	const eventData = {
		customerId,
		customerName: customerInfo.customerName,
		customerPhone: customerInfo.phone,
		eventType,
		eventName: getEventName(eventType),
		eventDescription: eventDescription || getDefaultEventDescription(eventType),
		eventTime: eventTime ? new Date(eventTime) : new Date(),
		consultantId: consultantId || customerInfo.consultantId,
		consultantName: consultantName || customerInfo.consultantName,
		propertyId: propertyId || '',
		propertyName: propertyName || '',
		amount: amount || 0,
		paymentType: paymentType || 0,
		contractNumber: contractNumber || '',
		documentUrls: documentUrls || [],
		imageUrls: imageUrls || [],
		previousStatus: previousStatus || customerInfo.status,
		currentStatus: currentStatus || customerInfo.status,
		intentionLevel: intentionLevel || customerInfo.intentionLevel,
		nextFollowTime: nextFollowTime ? new Date(nextFollowTime) : null,
		isImportant: isImportant || false,
		tags: tags || [],
		createTime: Date.now(),
		updateTime: Date.now(),
		visitType,
		operatorName,
		uid
	};

	// 如果是状态变更事件，更新客户状态
	if (currentStatus && currentStatus !== customerInfo.status) {
		await customerCollection.doc(customerId).update({
			status: currentStatus,
			intentionLevel: intentionLevel || customerInfo.intentionLevel,
			updateTime: Date.now()
		});
	}

	const res = await collection.add(eventData);

	return {
		code: 200,
		resultCode: 0,
		data: {
			eventId: res.id,
			customerStatus: currentStatus || customerInfo.status
		},
		message: '事件记录成功'
	};
}

module.exports = {

	// 获取客户生命周期历史
	async getCustomerLifecycle(params) {
		const {
			customerId,
			page = 1,
			pageSize = 20,
			eventType,
			getAll = false // 新增参数，是否获取所有记录
		} = params;

		let whereCondition = {
			customerId
		};

		if (eventType) {
			whereCondition.eventType = eventType;
		}

		if (getAll) {
			// 使用聚合查询突破100条限制
			const res = await db.collection('customer-lifecycle-history')
				.aggregate()
				.match(whereCondition)
				.sort({
					eventTime: -1
				})
				.limit(1000) // 聚合查询可以设置更大的限制，最大1000
				.end();

			return {
				code: 200,
				resultCode: 0,
				data: res.data,
				message: '获取成功'
			};
		} else {
			// 普通分页查询
			const res = await collection
				.where(whereCondition)
				.orderBy('eventTime', 'desc')
				.skip((page - 1) * pageSize)
				.limit(pageSize)
				.get();

			return {
				code: 200,
				resultCode: 0,
				data: res.data,
				message: '获取成功'
			};
		}
	},

	// 获取客户生命周期统计
	async getLifecycleStats(params) {
		const {
			customerId
		} = params;
		const db = uniCloud.database();
		const collection = db.collection('customer-lifecycle-history');

		// 获取所有事件
		const eventsRes = await collection
			.where({
				customerId
			})
			.orderBy('eventTime', 'asc')
			.get();

		const events = eventsRes.data;

		if (events.length === 0) {
			return {
				code: 0,
				data: {
					totalEvents: 0,
					firstEventTime: null,
					lastEventTime: null,
					importantEvents: 0,
					currentStage: '未开始',
					timeline: []
				},
				message: '暂无事件记录'
			};
		}

		// 计算统计信息
		const importantEvents = events.filter(event => event.isImportant).length;
		const firstEvent = events[0];
		const lastEvent = events[events.length - 1];

		// 判断当前阶段
		const currentStage = this.getCurrentStage(events);

		// 构建时间线
		const timeline = events.map(event => ({
			eventType: event.eventType,
			eventName: event.eventName,
			eventTime: event.eventTime,
			consultantName: event.consultantName,
			description: event.eventDescription,
			isImportant: event.isImportant
		}));

		return {
			code: 0,
			data: {
				totalEvents: events.length,
				firstEventTime: firstEvent.eventTime,
				lastEventTime: lastEvent.eventTime,
				importantEvents,
				currentStage,
				timeline
			},
			message: '获取成功'
		};
	},

	// 添加带看记录
	async addPropertyViewing(params) {
		const {
			customerId,
			propertyId,
			propertyName,
			viewingTime,
			consultantId,
			consultantName,
			impression,
			nextStep,
			imageUrls
		} = params;

		return await this.addLifecycleEvent({
			customerId,
			eventType: 5, // 房源带看
			eventDescription: `带看房源：${propertyName}。客户印象：${impression}。后续计划：${nextStep}`,
			eventTime: viewingTime,
			consultantId,
			consultantName,
			propertyId,
			propertyName,
			imageUrls,
			tags: ['带看', propertyName]
		});
	},

	async addFenPeiRecord(params) {
		const {
			customerId,
			customerName,
			consultantId
		} = params;
		const consultantCollection = db.collection('sunny-users');
		const consultantRes = await consultantCollection.doc(consultantId).get();

		if (consultantRes.data.length === 0) {
			return {
				code: 200,
				resultCode: -1,
				message: '置业顾问不存在'
			};
		}

		const consultantInfo = consultantRes.data[0];
		const consultantName = consultantInfo.nickName // 根据实际字段名调整

		const eventDescription = `把客户${customerName}分配给置业顾问${consultantName}`;
		const eventTime = Date.now();

		return addLifecycleEvent({
			customerId,
			eventType: 3, // 分配顾问，根据你的枚举应该是3不是2
			eventDescription,
			eventTime,
			consultantId,
			consultantName,
		});
	},

	// 添加付款记录
	async addPaymentRecord(params) {
		const {
			customerId,
			amount,
			paymentType,
			paymentTime,
			contractNumber,
			documentUrls,
			description
		} = params;

		return await this.addLifecycleEvent({
			customerId,
			eventType: 9, // 付款
			eventDescription: `付款金额：${amount}元。${description}`,
			eventTime: paymentTime,
			amount,
			paymentType,
			contractNumber,
			documentUrls,
			isImportant: true,
			tags: ['付款', `金额${amount}`]
		});
	},

	// 标记客户流失
	async markCustomerLost(params) {
		const {
			customerId,
			reason,
			lostTime
		} = params;

		return await this.addLifecycleEvent({
			customerId,
			eventType: 13, // 客户流失
			eventDescription: `客户流失。原因：${reason}`,
			eventTime: lostTime,
			currentStatus: 6, // 流失客户状态
			isImportant: true,
			tags: ['流失', reason]
		});
	},

	// 重新激活客户
	async reactivateCustomer(params) {
		const {
			customerId,
			reason,
			activateTime
		} = params;

		return await this.addLifecycleEvent({
			customerId,
			eventType: 14, // 重新激活
			eventDescription: `客户重新激活。原因：${reason}`,
			eventTime: activateTime,
			currentStatus: 4, // 意向客户状态
			tags: ['重新激活']
		});
	},
	// 添加跟进说明
	async addFollow(params,userInfo){
		const {
			customerId,
			content,
			type
		} = params;
		
		console.log(userInfo)
		
		// gouTList:[{
		// 	text:'到访',
		// 	value:'visit'
		// },{
		// 	text:'电话沟通',
		// 	value:'call'
		// },
		// {
		// 	text:'微信沟通',
		// 	value:'wechat'
		// }],
		
		return await addLifecycleEvent({
			customerId,
			eventType: 17, 
			eventDescription: `${content}`,
			visitType:type,
			uid:userInfo._id,
			operatorName:userInfo.nickName
		});
	}
};